var createNonceStr = function() {
    return Math.random().toString(36).substr(2, 15);
};

var createTimestamp = function() {
    return parseInt(new Date().getTime() / 1000) + '';
};

var raw = function(args) {
    var keys = Object.keys(args);
    var newArgs = [];
    keys.forEach(function(key) {
        newArgs.push(args[key])
    });
    newArgs = newArgs.sort()
    var string = newArgs.join('');
    return string;
};

/**
 * @synopsis 签名算法
 *
 * @param jsapi_ticket 用于签名的 jsapi_ticket
 *
 * @returns
 */
var sign = function(api_ticket, openid, card_id) {
    var ret = {
        api_ticket: api_ticket,
        nonce_str: createNonceStr(),
        timestamp: createTimestamp(),
        card_id: card_id,
    };
    var string = raw(ret);
    console.log("排序后:" + string)
    jsSHA = require('../routes/sha.js');
    shaObj = new jsSHA(string, 'TEXT');
    ret.signature = shaObj.getHash('SHA-1', 'HEX');
    return ret;
};

module.exports = sign;